<?php

class Blog_Controller_Browse_Add extends Nuo_Controller_Member
{
	function execute($request)
	{

		if (!Nuo::allow('blog.addNew'))
		{
			return 'could not process this page';
			return;
		}

		$table = Nuo::getTable('blog/post');

		$mainResourceId = $request -> getParam('main-resource');

		$poster = Nuo::getUser();

		$userId = Nuo::getUserId();

		if ($mainResourceId)
		{
			$mainResource = Nuo::getItem($mainResourceId);
		}

		if (!$mainResource)
		{
			$mainResource = Nuo::getUser();
		}

		/**
		 * check privacy
		 */
		if (!$mainResource -> isAllow('blog.new'))
		{
			return 'does not allow to pass this privacy';
			return;
		}

		$form = Nuo::getObject('blog/browse/add', 'form');

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			$item = $table -> fetchNew();

			$filter = Nuo::getApi('core/inputfilter');

			$data['title'] = $filter -> cleanText($data['title']);

			$data['content'] = $filter -> cleanHtml($data['content']);

			$item -> fromArray($data);

			$item -> created_at = time();

			$item -> user_id = $userId;

			$item -> setPoster($poster) -> setResource($mainResource);

			$item -> save();

			Nuo::getApi('activity') -> addFeed($poster, $mainResource, $item, 'blog:postedNewBlog');

			$uri = $mainResource -> getUrl('?tab=blog');

			Nuo::redirect($uri);
		}

		return Nuo::getView() -> render('core/view/controller/browse/edit', array('form' => $form));
	}

}
